package com.example.service;

import com.alibaba.cola.statemachine.StateMachine;
import com.alibaba.cola.statemachine.StateMachineFactory;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.config.SysSmsStateMachineConfig;
import com.example.context.Context;
import com.example.dao.SysSmsDao;
import com.example.enums.Events;
import com.example.enums.Status;
import com.example.po.SysSms;
import org.springframework.stereotype.Service;

@Service
public class SysSmsServiceImpl extends ServiceImpl<SysSmsDao, SysSms> implements SysSmsService {

    private StateMachine stateMachine;

    @Override
    public SysSms applySms() {
        SysSms sysSms = new SysSms();
        sysSms.setStatus(Status.READY);
        saveOrUpdate(sysSms);
        return sysSms;
    }

    @Override
    public boolean sendSms(Long id) {
        SysSms sysSms = getById(id);
        sysSms.setStatus(Status.SUCCESS);
        return sendEvents(Status.READY, Events.SUCCESSED, new Context(sysSms)) == Status.SUCCESS && saveOrUpdate(sysSms);
    }

    @Override
    public boolean commitSms(Long id) {
        SysSms sysSms = getById(id);
        sysSms.setStatus(Status.COMMIT);
        return sendEvents(Status.SUCCESS, Events.COMMITED, new Context(sysSms)) == Status.COMMIT && saveOrUpdate(sysSms);
    }

    @Override
    public Status sendEvents(Status status, Events events, Context context) {
        return (Status) getStateMachine().fireEvent(status, events, context);
    }


    @Override
    public StateMachine getStateMachine() {
        if (this.stateMachine == null) {
            this.stateMachine = StateMachineFactory.get(SysSmsStateMachineConfig.ID);
        }
        return this.stateMachine;
    }
}
